#!/bin/bash

# 创建应用商店数据库及用户的脚本
# 使用方法: ./create-database.sh root_password

# 检查是否提供了MySQL root密码
if [ -z "$1" ]; then
    echo "错误: 请提供MySQL root密码作为参数"
    echo "用法: $0 root_password"
    exit 1
fi

# 设置变量
ROOT_PASSWORD=$1
DB_NAME="appstore"
DB_USER="appstore"
DB_PASSWORD="Appstore778!"

# 创建数据库和用户的SQL命令
SQL_COMMAND="
CREATE DATABASE IF NOT EXISTS $DB_NAME character set utf8mb4;
CREATE USER IF NOT EXISTS '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASSWORD';
GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost';
FLUSH PRIVILEGES;
"

# 执行SQL命令
echo "正在创建数据库和用户..."
mysql -u root -p"$ROOT_PASSWORD" -e "$SQL_COMMAND"

# 检查MySQL命令是否执行成功
if [ $? -ne 0 ]; then
    echo "创建数据库和用户失败"
    exit 1
fi

echo "数据库和用户创建成功！"
echo "数据库名: $DB_NAME"
echo "用户名: $DB_USER"
echo "密码: $DB_PASSWORD"
echo "请妥善保管这些凭据！"

# 可选：导入数据库结构
read -p "是否要导入数据库结构？(y/n): " import
if [ "$import" = "y" ] || [ "$import" = "Y" ]; then
    echo "正在导入数据库结构..."
    mysql -u "$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" < data.sql
    if [ $? -ne 0 ]; then
        echo "导入数据库结构失败"
        exit 1
    fi
    echo "数据库结构导入成功！"
fi

exit 0    